package handlers

import (
	"data_service/server/websocket"
	"github.com/gin-gonic/gin"
	"github.com/zeromicro/go-zero/core/logx"
	"net/http"
)

// WebSocketHandler 处理WebSocket连接请求
// 功能: 接收客户端WebSocket连接请求，验证参数后转发给server/websocket模块处理
// 参数:
//   - c: Gin上下文，用于获取请求参数和响应
//
// 返回值: 无
func WebSocketHandler(c *gin.Context) {
	userID := c.Query("user_id")
	roomID := c.Query("room_id")
	userName := c.Query("user_name")

	// 参数验证
	if userID == "" || roomID == "" {
		logx.Errorf("[WebSocketHandler] 缺少必要参数: user_id=%s, room_id=%s", userID, roomID)
		c.JSON(http.StatusBadRequest, gin.H{"error": "missing user_id or room_id"})
		return
	}

	// 获取WebSocketServer实例
	wsServer := websocket.GetDefaultServer()
	if wsServer == nil {
		logx.Error("[WebSocketHandler] WebSocketServer实例未初始化")
		c.JSON(http.StatusInternalServerError, gin.H{"error": "server not initialized"})
		return
	}

	// 日志记录连接信息
	logx.Infof("[WebSocketHandler] 用户 %s(%s) 尝试加入房间 %s", userName, userID, roomID)

	// 调用server/websocket模块的ServeWS方法
	wsServer.ServeWS(c.Writer, c.Request, userID, roomID, userName)
}
